package com.pactera.redis.autoconfigure;

import com.pactera.redis.service.RedissonLocker;
import com.pactera.redis.utils.LockUtils;
import com.pactera.redis.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Redis配置
 *
 * @author: liqingdian
 */
@Configuration
@AutoConfigureBefore({org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({RedissonConfiguration.class, RedisConfiguration.class, LockConfiguration.class})
public class RedisAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(RedisAutoConfiguration.class);

    @Autowired
    private RedisProperties redisProperties;

    /**
     * redisTemplate配置
     *
     * @author: liqingdian
     */
    @Bean
    @ConditionalOnBean(name = "redisTemplate")
    @ConditionalOnMissingBean
    public RedisUtils redisUtils(RedisTemplate redisTemplate) {
        // 初始化RedisUtils
        RedisUtils builder = RedisUtils.builder(redisTemplate, redisProperties.getPrefix(), redisProperties.getTtl(), redisProperties.isIgnoreCase());
        log.info("redis-RedisUtils初始化成功");
        return builder;
    }

    /**
     * redisson相关配置
     */
    @Bean
    @ConditionalOnBean(name = "redissonClient")
    @ConditionalOnMissingBean
    public RedissonLocker redissonLocker(RedissonClient redissonClient) {
        RedissonLocker redissonLocker = new RedissonLocker(redissonClient);
        return redissonLocker;
    }

    @Bean
    @ConditionalOnBean(name = "redissonLocker")
    @ConditionalOnMissingBean
    public LockUtils lockUtils(RedissonLocker redissonLocker) {
        RedisProperties.RedissonProperties redissonProperties = redisProperties.getRedisson();
        String prefix = redissonProperties.getPrefix();
        if (StringUtils.isBlank(prefix)) {
            prefix = redisProperties.getPrefix();
        }
        LockUtils builder = LockUtils.builder(redissonLocker, prefix);
        log.info("redis-LockUtils初始化成功");
        return builder;
    }
}
